using DocumentCreationSystem.Services;
using Microsoft.Win32;
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Media;

namespace DocumentCreationSystem.Views.Dialogs;

/// <summary>
/// AI工具结果显示对话框
/// </summary>
public partial class AIToolResultDialog : Window
{
    private readonly AIToolExecutionResult _result;

    public AIToolResultDialog(AIToolExecutionResult result)
    {
        InitializeComponent();
        
        _result = result;
        InitializeDialog();
        LoadResult();
    }

    /// <summary>
    /// 初始化对话框
    /// </summary>
    private void InitializeDialog()
    {
        Title = $"工具执行结果 - {_result.ToolId}";
        
        // 根据执行结果设置标题栏颜色和图标
        if (_result.IsSuccess)
        {
            HeaderBackground.Color = Color.FromRgb(76, 175, 80); // 绿色
            StatusIcon.Text = "✓";
            ResultTitleText.Text = "工具执行成功";
        }
        else
        {
            HeaderBackground.Color = Color.FromRgb(244, 67, 54); // 红色
            StatusIcon.Text = "✗";
            ResultTitleText.Text = "工具执行失败";
        }
    }

    /// <summary>
    /// 加载执行结果
    /// </summary>
    private void LoadResult()
    {
        // 基本信息
        ToolIdText.Text = $"工具ID: {_result.ToolId}";
        ExecutionTimeText.Text = $"执行时间: {_result.ExecutionTimeMs}ms";
        
        StatusText.Text = _result.IsSuccess ? "成功" : "失败";
        StatusText.Foreground = _result.IsSuccess ? Brushes.Green : Brushes.Red;
        
        MessageText.Text = _result.Message;
        
        ExecutionTimeDetailText.Text = $"{_result.ExecutionTimeMs}ms";
        ExecutionDateText.Text = $"({_result.ExecutedAt:yyyy-MM-dd HH:mm:ss})";

        // 错误信息
        if (!_result.IsSuccess && !string.IsNullOrEmpty(_result.ErrorDetails))
        {
            ErrorHeader.Visibility = Visibility.Visible;
            ErrorText.Visibility = Visibility.Visible;
            ErrorText.Text = _result.ErrorDetails;
        }

        // 结果数据
        LoadResultData();

        // 执行日志
        LoadExecutionLogs();
    }

    /// <summary>
    /// 加载结果数据
    /// </summary>
    private void LoadResultData()
    {
        try
        {
            if (_result.Data.Any())
            {
                var jsonOptions = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };

                var jsonString = JsonSerializer.Serialize(_result.Data, jsonOptions);
                DataTextBox.Text = jsonString;
            }
            else
            {
                DataTextBox.Text = "无输出数据";
            }
        }
        catch (Exception ex)
        {
            DataTextBox.Text = $"数据序列化失败: {ex.Message}\n\n原始数据:\n{string.Join("\n", _result.Data.Select(kvp => $"{kvp.Key}: {kvp.Value}"))}";
        }
    }

    /// <summary>
    /// 加载执行日志
    /// </summary>
    private void LoadExecutionLogs()
    {
        LogsListBox.Items.Clear();
        
        if (_result.Logs.Any())
        {
            foreach (var log in _result.Logs)
            {
                LogsListBox.Items.Add(log);
            }
        }
        else
        {
            LogsListBox.Items.Add("无执行日志");
        }
    }

    /// <summary>
    /// 复制数据按钮点击事件
    /// </summary>
    private void CopyDataButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(DataTextBox.Text))
            {
                Clipboard.SetText(DataTextBox.Text);
                MessageBox.Show("数据已复制到剪贴板", "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"复制失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 保存数据按钮点击事件
    /// </summary>
    private void SaveDataButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var saveDialog = new SaveFileDialog
            {
                Title = "保存工具执行结果",
                Filter = "JSON文件 (*.json)|*.json|文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                DefaultExt = "json",
                FileName = $"{_result.ToolId}_result_{DateTime.Now:yyyyMMdd_HHmmss}"
            };

            if (saveDialog.ShowDialog() == true)
            {
                var content = DataTextBox.Text;
                if (string.IsNullOrEmpty(content))
                {
                    content = "无数据";
                }

                File.WriteAllText(saveDialog.FileName, content);
                MessageBox.Show($"结果已保存到: {saveDialog.FileName}", "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 复制日志按钮点击事件
    /// </summary>
    private void CopyLogsButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (_result.Logs.Any())
            {
                var logsText = string.Join("\n", _result.Logs);
                Clipboard.SetText(logsText);
                MessageBox.Show("日志已复制到剪贴板", "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"复制失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 重新执行按钮点击事件
    /// </summary>
    private void RetryButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // 触发重新执行事件
            RetryRequested?.Invoke(_result.ToolId);
            Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"重新执行失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 关闭按钮点击事件
    /// </summary>
    private void CloseButton_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }

    /// <summary>
    /// 重新执行请求事件
    /// </summary>
    public event Action<string>? RetryRequested;

    /// <summary>
    /// 获取执行结果摘要
    /// </summary>
    public string GetResultSummary()
    {
        var status = _result.IsSuccess ? "成功" : "失败";
        var dataCount = _result.Data.Count;
        var logCount = _result.Logs.Count;
        
        return $"工具: {_result.ToolId}\n" +
               $"状态: {status}\n" +
               $"执行时间: {_result.ExecutionTimeMs}ms\n" +
               $"数据项: {dataCount}\n" +
               $"日志条数: {logCount}\n" +
               $"消息: {_result.Message}";
    }

    /// <summary>
    /// 导出完整报告
    /// </summary>
    public void ExportFullReport()
    {
        try
        {
            var saveDialog = new SaveFileDialog
            {
                Title = "导出完整执行报告",
                Filter = "HTML文件 (*.html)|*.html|文本文件 (*.txt)|*.txt",
                DefaultExt = "html",
                FileName = $"{_result.ToolId}_report_{DateTime.Now:yyyyMMdd_HHmmss}"
            };

            if (saveDialog.ShowDialog() == true)
            {
                var report = GenerateFullReport();
                File.WriteAllText(saveDialog.FileName, report);
                MessageBox.Show($"完整报告已导出到: {saveDialog.FileName}", "导出成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 生成完整报告
    /// </summary>
    private string GenerateFullReport()
    {
        var report = $@"
# AI工具执行报告

## 基本信息
- 工具ID: {_result.ToolId}
- 执行状态: {(_result.IsSuccess ? "成功" : "失败")}
- 执行时间: {_result.ExecutionTimeMs}ms
- 执行日期: {_result.ExecutedAt:yyyy-MM-dd HH:mm:ss}
- 结果消息: {_result.Message}

## 错误信息
{(_result.ErrorDetails ?? "无错误")}

## 输出数据
```json
{DataTextBox.Text}
```

## 执行日志
```
{string.Join("\n", _result.Logs)}
```

---
报告生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}
";

        return report;
    }
}
